<?php

/**
 * This is the model class for table "products".
 *
 * The followings are the available columns in table 'products':
 * @property string $id
 * @property string $name_en
 * @property string $name_th
 * @property string $description_en
 * @property string $description_th
 * @property string $created_date
 * @property string $updated_date
 * @property integer $enable
 * @property string $product_category_id
 * @property string $slug
 * @property integer $display_order
 * @property integer $active_flag
 * @property integer $default_photo_id
 *
 * The followings are the available model relations:
 * @property ProductPhotos[] $productPhotoses
 * @property ProductCategories $productCategory
 * @property ProductPhotos $defaultPhotos
 */
class Products extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Products the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'products';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name_en, product_category_id', 'required'),
			array('enable, display_order, active_flag, default_photo_id', 'numerical', 'integerOnly'=>true),
			array('name_en, name_th, slug', 'length', 'max'=>200),
			array('product_category_id', 'length', 'max'=>10),
			array('description_en, description_th, created_date, updated_date', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, name_en, name_th, description_en, description_th, created_date, updated_date, enable, product_category_id, slug, display_order, active_flag, default_photo_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'photosCount'=>array(self::STAT, 'ProductPhotos', 'product_id'),
			'productPhotoses' => array(self::HAS_MANY, 'ProductPhotos', 'product_id'),
			'productCategory' => array(self::BELONGS_TO, 'ProductCategories', 'product_category_id'),
			'defaultPhoto' => array(self::BELONGS_TO, 'ProductPhotos', 'default_photo_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name_en' => 'Name En',
			'name_th' => 'Name Th',
			'description_en' => 'Description En',
			'description_th' => 'Description Th',
			'created_date' => 'Created Date',
			'updated_date' => 'Updated Date',
			'enable' => 'Enable',
			'product_category_id' => 'Product Category',
			'slug' => 'Slug',
			'display_order' => 'Display Order',
			'active_flag' => 'Active Flag',
			'default_photo_id' => 'Default Photos',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('name_en',$this->name_en,true);
		$criteria->compare('name_th',$this->name_th,true);
		$criteria->compare('description_en',$this->description_en,true);
		$criteria->compare('description_th',$this->description_th,true);
		$criteria->compare('created_date',$this->created_date,true);
		$criteria->compare('updated_date',$this->updated_date,true);
		$criteria->compare('enable',$this->enable);
		$criteria->compare('product_category_id',$this->product_category_id,true);
		$criteria->compare('slug',$this->slug,true);
		$criteria->compare('display_order',$this->display_order);
		$criteria->compare('active_flag',$this->active_flag);
		$criteria->compare('default_photo_id',$this->default_photo_id);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
  public function behaviors(){
    return array(
      'sluggable' => array(
        'class'=>'ext.SluggableBehavior.SluggableBehavior',
        'columns' => array('name_en'),
        'unique' => true,
        'update' => true,
      ),
    );
  }


  public function beforeSave() {	
    if ($this->isNewRecord) {
      $this->display_order = $this->_nextDisplayOrder();
      $this->created_date = new CDbExpression('NOW()');
    }else {
      $this->updated_date = new CDbExpression('NOW()');
    }
    return parent::beforeSave();
  }

  //virtual field
  public function getName()
  {
    $ret = $this->name_en;

    if (isset($_GET['language'])) {
      switch ($_GET['language']) {
        case "th":
          $data = $this->name_th;
          $ret = (isset($data) && ($data!=''))  ? $data : $ret;
          break;
        default:
          $ret = $this->name_en;
      }
    }

    return $ret;
  }

  public function getShortDescription()
  {
    $ret = $this->short_description_en;

    if (isset($_GET['language'])) {
      switch ($_GET['language']) {
        case "th":
          $data = $this->short_description_th;
          $ret = (isset($data) && ($data!=''))  ? $data : $ret;
          break;
        default:
          $ret = $this->short_description_en;
      }
    }

    return $ret;
  }

  public function getDescription()
  {
    $ret = $this->description_en;

    if (isset($_GET['language'])) {
      switch ($_GET['language']) {
        case "th":
          $data = $this->description_th;
          $ret = (isset($data) && ($data!=''))  ? $data : $ret;
          break;
        default:
          $ret = $this->description_en;
      }
    }

    return $ret;
  }

  public function getThumbnailPath()
  {
    if (($lastDotPosition = strrpos($this->image_path, '.')) == true) {
      return substr_replace($this->image_path, '_t', $lastDotPosition, 0);
    }else {
      return null;
    }
  }

  public function getMaxDisplayOrder()
  {
    $criteria = new CDbCriteria;
    $criteria->select='MAX(display_order) as display_order';
    $criteria->compare('enable', 1);
    $criteria->compare('product_category_id', $this->product_category_id);	
    $model = $this->find($criteria);
    return $model->display_order;
  }

  public function _nextDisplayOrder()
  {
    $max = $this->getMaxDisplayOrder();
    $ret = isset($max) ? ($max+1) : 1;
    return $ret;
  }		
}